from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User 

from conference.models import Conference
from Profile.models import UserProfile, UserConf
from wype.forms import RegistrationForm, ConferenceRegistration

# main page
def index(request):
	return render_to_response('index.html', {'loggedin': request.user.is_authenticated(),
								'conferences': Conference.objects.all()},
					context_instance=RequestContext(request))

# login page
def login(request):
	# if it's an http POST
	if request.method == 'POST':
		username = request.POST.get('username', '')
		password = request.POST.get('password', '')
		user = auth.authenticate(username=username, password=password)
		# if they auth'd fine, log them in, else display errors
		if user is not None and user.is_active:
			auth.login(request, user)
			return render_to_response('index.html', {'errors': False, 
									'loggedin':user.is_authenticated(),
									'conferences':Conference.objects.all()},
							context_instance=RequestContext(request)) 
		else:
			return render_to_response('login.html', {'errors': True,
											'loggedin': request.user.is_authenticated()},
							context_instance=RequestContext(request))
	# else it's just a GET
	return render_to_response('login.html', {'errors': False, 
											'loggedin':request.user.is_authenticated()}, 
							context_instance=RequestContext(request))

# logs the user out and redirects them to the main page
def logout(request):
	auth.logout(request)
	return render_to_response('index.html', {'loggedin': request.user.is_authenticated(),
					'conferences':Conference.objects.all()},
							context_instance=RequestContext(request))

# displays the user's profile, or if they're not logged in, redirects them
# over to the login page
def profile(request):
	if not request.user.is_authenticated():
		return render_to_response('login.html', {'loggedin': request.user.is_authenticated()},
							context_instance=RequestContext(request))
	else:
		# generate a list of all the conferences they're attending and display it
		# on their profile page
		user_conferences = []
		uconf = request.user.profile.conf.all()
		for i in uconf.all():
			user_conferences.append(Conference.objects.get(name=i.conf))
		return render_to_response('profile.html', {'loggedin': request.user.is_authenticated(),
								  'conference':user_conferences},
							context_instance=RequestContext(request))
	
# about page
def about(request):
	return render_to_response('about.html', {'loggedin': request.user.is_authenticated()},
							context_instance=RequestContext(request))

# edits a profile
def edit_profile(request):
		if request.method == 'POST':
			username = request.POST.get('username', '')
			first_name = request.POST.get('first_name', '')
			last_name = request.POST.get('last_name', '')
			email = request.POST.get('email', '')
			company = request.POST.get('company', '')

			usr = User.objects.get(username__exact=username)
			profile = usr.get_profile() 
			usr.username = username
			usr.first_name = first_name
			usr.last_name = last_name
			usr.email = email
			profile.company = company
			profile.save()
			usr.save()
			return render_to_response('profile.html', {'loggedin': request.user.is_authenticated(), 
													  'user': request.user},
							context_instance=RequestContext(request))
		else:
			if request.user.is_authenticated():
				return render_to_response('edit_profile.html', {'loggedin': True,
							'user':request.user}, context_instance=RequestContext(request))
			else:
				return HttpResponseRedirect('/login/')

# register a new user and profile
def register(request):
	errors = False
	f = RegistrationForm()
	# if it's a POST, they're submitting the form 
	if request.method == 'POST':
		username = request.POST.get('username', '')
		email = request.POST.get('email', '')
		first_name = request.POST.get('first_name', '')
		last_name = request.POST.get('last_name', '')
		company = request.POST.get('company', '')
		password = request.POST.get('password1', '')
		password2 = request.POST.get('password2', '')
		# this isn't a safe way to do password stuff, but this website's traffic doesn't
		# leave the local machine, so whatever.  They're encrypted in the sqlite3 db though.
		if password == password2:
			# generate their new account and profile, set the fields, and save them 
			user = User.objects.create_user(username=username, email=email, password=password)
			profile = UserProfile.objects.create(user=user)
			user.first_name = first_name
			user.last_name = last_name
			profile.company = company
			profile.save()
			user.save()
			return HttpResponseRedirect('/login/') 
		else: 
			errors = True	
			f = RegistrationForm(request.POST)
	# it's either a GET or a failed registration attempt
	return render_to_response('register_user.html', {'form': f, 'errors': errors},
						context_instance=RequestContext(request))

# register a new conference
def register_conf(request):
	errors = False
	if request.method == 'POST':
		f = ConferenceRegistration(request.POST, request.FILES)
		if f.is_valid():
			name = request.POST.get('name', '')
			company = request.POST.get('company', '')
			location = request.POST.get('location', '')
			public = request.POST.get('public', '')
			# for some reason this doesn't return T or F, but 'on' or blank lol
			if 'on' == public:
				public = True
			else:
				public = False
			date = request.POST.get('date', '')
			cost = request.POST.get('cost', '')
			room = request.POST.get('room', '')
			conference = Conference(name=name, company=company, location=location,
						 public=public, date=date, cost=cost, room=room, itinerary=request.FILES.get('file'))
			conference.save()
			# add them as an administrator
			conference.admins.add(request.user.get_profile())
			# set their user conf
			conf = UserConf.objects.create(conf=name, registered=True, paid=True)
			conf.save()
			uprofile = request.user.get_profile()
			uprofile.conf.add(conf)
			return render_to_response('index.html', {'loggedin': True, 
							'conferences': Conference.objects.all()},
							context_instance=RequestContext(request))
		else:
			errors = True
	else:
		f = ConferenceRegistration()
	# it's either a GET or a failed reg
	return render_to_response('register_conference.html', {'loggedin':request.user.is_authenticated(),
						'form': f, 'errors': errors}, context_instance=RequestContext(request))

# called when we're generating the page of a specific conference.  This is where we're mapped to 
# from the index page, for example
def spec_conference(request, conference):
	conf = Conference.objects.get(name=conference)
	is_regd = False
	is_paid = False
	checked = False
	admin = False
	itinerary = False
	# if they're not logged in, we need to redirect them to login
	if request.user.is_authenticated():
		# get all of their configs
		uconf = request.user.profile.conf.all()
		# check and see if the conference is in their reg'd table
		for i in uconf.all():
			if i.conf == conference:
				is_regd = True
				if i.paid:
					is_paid = True
				if i.checked_in:
					checked = True
				if conf.itinerary.name:
					itinerary = True
				break
		# now check if the user is an admin of the conference
		for i in conf.admins.all():
			if str(i.user) == str(request.user.username):
				admin = True

		return render_to_response('conference.html', 
						{'loggedin': True, 'conference':conf, 'is_regd':is_regd, 
						'paid': is_paid, 'admin': admin, 'checked': checked,
						'itinerary':itinerary},
						context_instance=RequestContext(request))
	else:
		return HttpResponseRedirect('/login/')

# add currently logged in user to the conference
def add_user_to_conference(request, conference):
	conf = Conference.objects.get(name=conference)
	# if they're not logged in, we need to redirect them to login
	if request.user.is_authenticated():
		# create a user conference object and mark it as registered
		uconf = UserConf.objects.create(conf=conf.name, registered=True, paid=False)
		uconf.save()
		# add the model to their account
		uprofile = request.user.get_profile()
		uprofile.conf.add(uconf)
		# redirect them
		return render_to_response('conference.html', {'loggedin': True, 'conference':conf,
									'is_regd':True}, 
						context_instance=RequestContext(request))
	else:
		return HttpResponseRedirect('/login/')
